package com.dwin.h5.app.ui.pages;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dwin.h5.app.H5Application;
import com.dwin.h5.app.R;
import com.dwin.h5.app.esptouch.EsptouchTask;
import com.dwin.h5.app.esptouch.IEsptouchResult;
import com.dwin.h5.app.models.ConfigureDeviceInfo;
import com.dwin.h5.app.ui.BaseActivity;
import com.dwin.h5.app.utils.Constants;
import com.dwin.h5.app.utils.MobileUtil;
import com.dwin.h5.app.utils.ToastUtil;
import com.dwin.h5.app.views.dialogs.ConfigWifiDialog;
import java.util.ArrayList;
import java.util.List;

/**
 * 给硬件设备配置网络 UI2.0 2019.11.27
 * 配网页面，原生Native实现
 */
@Deprecated
public class ConfigureNetActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "ConfigureNetActivity";
    private static final int GPS_REQUEST_CODE = 456; // 打开GPS的请求码
    private static final int WIFI_REQUEST_CODE = 457; // wifi 判断修改的请求码

    private TextView tvTitle;
    private ImageView iv_config_wifi;
    private RelativeLayout rl_body_2config, rl_body_configing, rl_body_failed;
    private ImageView ivRotateLoading; //
    private Button btn_start_config;

    // private String wifiPwd; // 保存的wifi密码
    //--------------设备配网参数----------------
    private WifiManager wifimanager;
    private String mCurrentSSID;
    private volatile List<ScanResult> mScanResultList;
    private volatile List<String> mScanResultSsidList;

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                updateCurrentConnectionInfo();
            }
        }
    };

    /**
     * 获取SSID
     *
     * @param activity 上下文
     * @return WIFI 的SSID
     */
    public String getWIFISSID(Activity activity) {
        String ssid = "unknown id";
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O
                || Build.VERSION.SDK_INT == Build.VERSION_CODES.P
                || Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) {
            WifiManager mWifiManager = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            assert mWifiManager != null;
            WifiInfo info = mWifiManager.getConnectionInfo();
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                return info.getSSID();
            } else {
                return info.getSSID().replace("\"", "");
            }
        } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O_MR1) {
            ConnectivityManager connManager = (ConnectivityManager) activity.getApplicationContext()
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            assert connManager != null;
            NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isConnected()) {
                if (networkInfo.getExtraInfo() != null) {
                    return networkInfo.getExtraInfo().replace("\"", "");
                }
            }
        }
        return ssid;
    }

    private void updateCurrentConnectionInfo() {
        mCurrentSSID = getWIFISSID(this);
        wifimanager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        if (mCurrentSSID == null) {
            mCurrentSSID = "";
        }
        if (!TextUtils.isEmpty(mCurrentSSID)) {
            scanWifi();
            for (int i = 0; i < mScanResultList.size(); i++) {
                String ssid = mScanResultList.get(i).SSID;
                if (mCurrentSSID.contains(ssid)) {
                    mCurrentSSID = ssid; // 当前网络ssid
                    Log.d(TAG, "ssid:" + mCurrentSSID);
                    break;
                }
            }
        }
    }

    //------------------------------------------
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_configure_net);
        initViews();

        // 动态申请运行时权限
        if (hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.CHANGE_WIFI_STATE)) {
            doCoarseLocation();
        } else {
            requestPermissions(Constants.COARSE_LOCATION_CODE,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.CHANGE_WIFI_STATE,
                    Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (!MobileUtil.isGpsOpen(this)) {
            new AlertDialog.Builder(this).setTitle("提示").setMessage("配网需要GPS权限，现在就去打开GPS?") // 拒绝, 退出应用
                    .setNegativeButton("取消",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    finish();
                                }
                            }).setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) { //跳转GPS设置界面
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, GPS_REQUEST_CODE);
                        }
                    }).setCancelable(false).show();
        }

        if (isWifi5G(this)) { // 判断wifi是否是5g判断
            new AlertDialog.Builder(this).setTitle("提示").setMessage("您的手机wifi是5G频段,不能配网。请先改成2.4G频段，再进行配网。") // 拒绝, 退出应用
                    .setPositiveButton("设置wifi频段为2.4G",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) { // 跳转WIFI设置界面
                                    Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                                    startActivityForResult(intent, WIFI_REQUEST_CODE);
                                }
                            }).setCancelable(false).show();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GPS_REQUEST_CODE && resultCode == RESULT_OK) {
            doCoarseLocation();
        }
    }

    @Override
    public void doCoarseLocation() {
        mScanResultList = new ArrayList<>();
        mScanResultSsidList = new ArrayList<>();
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, filter);
        updateCurrentConnectionInfo();
    }

    @Override
    protected void initViews() {
        Button btnLeft = findViewById(R.id.btn_header_left);
        btnLeft.setVisibility(View.VISIBLE);
        btnLeft.setOnClickListener(this);
        tvTitle = findViewById(R.id.tv_header_title);
        tvTitle.setText("WIFI配置");

        iv_config_wifi = findViewById(R.id.iv_config_wifi);
        iv_config_wifi.setBackgroundResource(R.drawable.anim_config_net);
        AnimationDrawable ad = (AnimationDrawable) iv_config_wifi.getBackground();
        ad.start();

        rl_body_2config = findView(R.id.rl_body_2config);
        rl_body_configing = findView(R.id.rl_body_configing);
        rl_body_failed = findView(R.id.rl_body_failed);

        btn_start_config = findViewById(R.id.btn_start_config);
        btn_start_config.setOnClickListener(this);
        findViewById(R.id.tv_config_info).setOnClickListener(this);

        ivRotateLoading = findView(R.id.iv_config_anim);
        ivRotateLoading.setBackgroundResource(R.drawable.anim_configing_net);
        AnimationDrawable adLoading = (AnimationDrawable) ivRotateLoading.getBackground();
        adLoading.start();
        findViewById(R.id.btn_config_again).setOnClickListener(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
            mReceiver = null;
        }
        ivRotateLoading.clearAnimation();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_header_left:
                finish();
                break;

            case R.id.tv_config_info:
                break;

            case R.id.btn_start_config: // 开始配置网络
                if (!isWifiConnect()) {
                    ToastUtil.toastShort(this, "请先连接wifi");
                    return;
                }
                String  wifiPwd = logMessage.getString("wifiPassword", null); // 获取之前保存的wifi密码
                final ConfigWifiDialog dialog = new ConfigWifiDialog(mContext, R.style.DialogTheme);
                dialog.setMyTitle("当前连接WIFI：" + mCurrentSSID);
                dialog.setCancelable(false);
                dialog.setMyPwd(wifiPwd); // 设置wifi密码
                dialog.setDialogListener(new ConfigWifiDialog.MyDialogListener() {
                    @Override
                    public void onClickPositive(String password) {
                        dialog.dismiss();
                        configureDeviceWifi(password);
                    }
                });
                dialog.show();
                break;

            case R.id.btn_config_again: // 重新配网
                if (mReceiver != null) {
                    unregisterReceiver(mReceiver);
                    mReceiver = null;
                }
                doCoarseLocation();

                tvTitle.setText("WIFI配置");
                rl_body_2config.setVisibility(View.VISIBLE);
                rl_body_configing.setVisibility(View.GONE);
                rl_body_failed.setVisibility(View.GONE);
                btn_start_config.performClick();
                break;
        }
    }

    //------------------------------------------
    private void configureDeviceWifi(String password) {
        if (!TextUtils.isEmpty(mCurrentSSID)) {
            String ssid = mCurrentSSID;
            boolean isSsidHidden = false;
            // find the bssid is scanList
            String bssid = scanApBssidBySsid(ssid);
            if (bssid == null) {
                Toast.makeText(this, getString(R.string.esp_esptouch_cannot_find_ap_hing, ssid), Toast.LENGTH_LONG).show();
            } else {
                new ConfigureTask(this, ssid, bssid, password, isSsidHidden).execute();
            }
        } else {
            Toast.makeText(this, R.string.esp_esptouch_connection_hint, Toast.LENGTH_LONG).show();
        }
    }

    private String scanApBssidBySsid(String ssid) {
        if (TextUtils.isEmpty(ssid)) {
            return null;
        }
        String bssid = null;
        for (int retry = 0; bssid == null && retry < 3; retry++) {
            scanWifi();
            for (ScanResult scanResult : mScanResultList) {
                if (scanResult.SSID.equals(ssid)) {
                    bssid = scanResult.BSSID;
                    return bssid;
                }
            }
        }
        return null;
    }

    private void scanWifi() {
        wifimanager.startScan();
        mScanResultList = wifimanager.getScanResults();
        mScanResultSsidList.clear();
        for (ScanResult scanResult : mScanResultList) {
            mScanResultSsidList.add(scanResult.SSID);
        }
    }

    // 配网过程
    private class ConfigureTask extends AsyncTask<String, Void, IEsptouchResult> implements DialogInterface.OnCancelListener {
        private Activity mActivity;
        private EsptouchTask mTask;
        private final String mSsid;
        private String mPassword;

        public ConfigureTask(Activity activity, String apSsid, String apBssid, String password, boolean isSsidHidden) {
            mActivity = activity;
            mSsid = apSsid;
            mPassword = password;
            mTask = new EsptouchTask(apSsid, apBssid, password, isSsidHidden, ConfigureNetActivity.this);
        }

        @Override
        protected void onPreExecute() {
            tvTitle.setText("设备配网中");
            rl_body_2config.setVisibility(View.GONE);
            rl_body_configing.setVisibility(View.VISIBLE);
            rl_body_failed.setVisibility(View.GONE);
        }

        @Override
        protected IEsptouchResult doInBackground(String... params) {
            return mTask.executeForResult();
        }

        @Override
        protected void onPostExecute(IEsptouchResult result) {
            int toastMsg;
            if (result.isSuc()) { // 配网成功--跳转到绑定设备页面,当前页面销毁
                // 保存当前wifi的密码
                logMessage.edit().putString("wifiPassword", mPassword).commit();

                toastMsg = R.string.esp_esptouch_result_suc;
                Toast.makeText(mActivity, toastMsg, Toast.LENGTH_LONG).show();
                ConfigureDeviceInfo configureInfo = new ConfigureDeviceInfo();
                configureInfo.bssid = result.getBssid(); // device bssid
                H5Application.device_bssid = configureInfo.bssid;
                configureInfo.hostAddress = result.getInetAddress().getHostAddress();
                configureInfo.address = result.getInetAddress().getAddress();
                Log.d("0402", "device_bssid:" + configureInfo.bssid);

                Intent data = new Intent();
                data.putExtra("device_bssid", configureInfo.bssid);
                setResult(RESULT_OK, data);
                finish();
            } else if (result.isCancelled()) { // 取消配置
                logMessage.edit().remove("wifiPassword").commit();
                toastMsg = R.string.esp_esptouch_result_cancel;
                Toast.makeText(mActivity, toastMsg, Toast.LENGTH_LONG).show();
                tvTitle.setText("WIFI配置");
                rl_body_2config.setVisibility(View.VISIBLE);
                rl_body_configing.setVisibility(View.GONE);
                rl_body_failed.setVisibility(View.GONE);
            } else if (mCurrentSSID.equals(mSsid)) { // 配置失败
                logMessage.edit().remove("wifiPassword").commit();

                tvTitle.setText("搜索并连接设备");
                rl_body_2config.setVisibility(View.GONE);
                rl_body_configing.setVisibility(View.GONE);
                rl_body_failed.setVisibility(View.VISIBLE);
            } else { // 配置结束，因当前连接的WIFI与配置的WIFI不同，无法收到反馈，请自行检查结果
                logMessage.edit().remove("wifiPassword").commit();

                toastMsg = R.string.esp_esptouch_result_over;
                Toast.makeText(mActivity, toastMsg, Toast.LENGTH_LONG).show();
                tvTitle.setText("WIFI配置");
                rl_body_2config.setVisibility(View.VISIBLE);
                rl_body_configing.setVisibility(View.GONE);
                rl_body_failed.setVisibility(View.GONE);
            }
        }

        @Override
        public void onCancel(DialogInterface dialog) {
            if (mTask != null) {
                mTask.interrupt();
                Toast.makeText(mActivity, R.string.esp_esptouch_result_cancel, Toast.LENGTH_LONG).show();
            }
        }
    }

    /**
     * 判断连接的wifi是否是5G 频段的
     *
     * @param context
     * @return
     */
    public static boolean isWifi5G(Context context) {
        int freq = 0;
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.LOLLIPOP) {
            freq = wifiInfo.getFrequency();
        } else {
            String ssid = wifiInfo.getSSID();
            if (ssid != null && ssid.length() > 2) {
                String ssidTemp = ssid.substring(1, ssid.length() - 1);
                List<ScanResult> scanResults = wifiManager.getScanResults();
                for (ScanResult scanResult : scanResults) {
                    if (scanResult.SSID.equals(ssidTemp)) {
                        freq = scanResult.frequency;
                        break;
                    }
                }
            }
        }
        return freq > 4900 && freq < 5900;
    }

}
